package medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// 排序+双指针
public class T15 {
    public static void main(String[] args) {
        System.out.println(new T15().threeSum(new int[]{-1,0,1,2,-1,-4,-2,-3,3,0,4}));
    }

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        for (int a = 0; a < nums.length - 2; a++) {
            // 需要和上一次枚举的数不相同
            if (a > 0 && nums[a] == nums[a - 1]) {
                continue;
            }
            if (nums[a] > 0) {
                return result;
            }
            int c = nums.length - 1;
            for (int b = a + 1; b < nums.length - 1; b++) {
                // 需要和上一次枚举的数不相同
                if (b > a + 1 && nums[b] == nums[b - 1]) {
                    continue;
                }
                while (true) {
                    if (c <= b) {
                        break;
                    }
                    if (nums[a] + nums[b] + nums[c] == 0) {
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(nums[a]);
                        list.add(nums[b]);
                        list.add(nums[c]);
                        result.add(list);
                        break;
                    } else if (nums[a] + nums[b] + nums[c] > 0) {
                        c--;
                    } else {
                        break;
                    }

                }

            }
        }
        return result;
    }
}
